package champPackage;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UserRegistrationServlet
 */
@WebServlet("/UserRegistrationServlet")
public class UserRegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserRegistrationServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String user = request.getParameter("user");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		DBManager db = DBManager.getInstance();
		try{
			if(db.userNameExists(user)){
				RequestDispatcher disp = request.getRequestDispatcher("UserNameExists.jsp");
				disp.forward(request, response);
			}
			else if(!User.isValidInfo(user, password, email)){
				RequestDispatcher disp = request.getRequestDispatcher("InvalidUserInfo.jsp");
				disp.forward(request, response);
			}
			else{
				db.addUserInfoToTheDatabase(user, password, email, "user");
				System.out.println("daemata");
				System.out.println(user);
				request.getSession().setAttribute("username", user);
				RequestDispatcher disp = request.getRequestDispatcher("HomeLoggedIn.jsp");
				disp.forward(request, response);
			}
		}
		catch(SQLException ex){
			ex.printStackTrace();
		}
	}

}
